//index.js
//获取应用实例
const app = getApp()
const config = require('../../utils/config.js');
const util = require('../../utils/util.js');
const auth = require('../../utils/auth.js');
const MIN = 60;
var SocketTask = null;
var socketOpen = false;
let sgin = '/'
let [mudid, email, uName, way] = [Math.floor(Math.random() * 9999999), 'neo@qq.com', 'neo', 'miniProgram'];
let [firstName, lastName] = ['testFrisName','testLastName'];
const url = config.webSocketUrl +
  sgin + mudid + sgin + email + sgin + uName + sgin + way;

// 录音
// 获取全局唯一的录音管理器 RecorderManager
const recorderManager = wx.getRecorderManager();
const fs = wx.getFileSystemManager()
// 录音取消flg true 取消;false录音
var recordFlg = false; 
var timer60s = null; // 60s check 未实现
var speakerInterval;
var feedbackFlg = false; // 为解决flg
const options = {
  duration: 6000,
  sampleRate: 16000,
  numberOfChannels: 1,
  encodeBitRate: 96000,
  format: 'mp3',
  frameSize: 50
}

Page({
  data: {
    scrollTop: 0,
    lastX: 0,
    lastY: 0,
    currentGesture: 0,
    keyboar_hidden: false,
    voice_hidden: true,
    allContentList: [],
    input_value: '',
    voice_value: '',
    isSpeaking: false,
    closeSpeaking: false,
    speakerUrl: '../../style/img/speaker0.png',
    speakerUrlPrefix: '../../style/img/speaker',
    speakerUrlSuffix: '.png',
    filePath: null,
    lasnAiAnswer:false,
    hostUrl: config.host,
    imagefiles: [],

  },

  onShow: function (options) {
    email = wx.getStorageSync("ACCOUNT");
    mudid = wx.getStorageSync("ACCOUNT");
    wx.startPullDownRefresh();
    console.log('mudid,',mudid)
    console.log('email,', email)
  },
  onUnload:function(){
    if (socketOpen){
      socketOpen = false;      
      SocketTask.close();
    }
  },
  // 下拉刷新
  onPullDownRefresh(){
    console.log("下拉")
    if (!socketOpen){
      console.log("下拉刷新成功")
      email = wx.getStorageSync("ACCOUNT");
      mudid = wx.getStorageSync("ACCOUNT");
      this.data.allContentList = [];//清空回话能容
      this.webSocket();
      this.onLoadMyData(); 
      util.showBusy('刷新成功.');
    } 
    wx.stopPullDownRefresh();
  },
  onLoadMyData: function() {
    if (!socketOpen) return;
    SocketTask.onOpen(res => {
      socketOpen = true;
      console.log("监听WebSocket 连接打开事件==> ", res, socketOpen);
    })
    SocketTask.onClose(res => {
      // if (!socketOpen) wx.startPullDownRefresh();
      socketOpen = false;
      // util.showSuccess('服务器连接关闭.');
      console.log("监听WebSocket 连接关闭事件==> ", res, socketOpen);
    })
    SocketTask.onError(res => {
      socketOpen = false;
      // util.showModel('连接服务器失败.', '请下拉刷新试试.');
      console.log("监听WebSocket 连错误事件==> ", res, socketOpen);
      SocketTask.close();
    })
    SocketTask.onMessage(res => {
      wx.hideToast();
      
      let result = JSON.parse(res.data);
      var that = this;
      let answerType = result.answerType;
      let questionList = result.questionList;
      let imagefiles = [];

      if(answerType == '2'){// 图文特殊处理
        if(questionList){
          questionList.forEach( (item,index)=>{
            imagefiles.push(
              that.data.hostUrl + '/policy' + item.pic,// 图片路径
            );
          }) 
        }
      }else if(answerType =='1'){// 图片特殊处理
        questionList.forEach((item, index) => {
          imagefiles.push(
            that.data.hostUrl + '/policy' + item.pic,// 图片路径
          );
        }) 
      } 
     that.setData({
       imagefiles: imagefiles,
       closeQuestion: result.closeQuestion,
     })
      console.log("imagefiles=>",imagefiles);
      that.data.allContentList.push({
        is_ai: true,
        defQuestion: result.defQuestion,
        answerType: result.answerType,//问题类型 0:默认文字1:图片2:图文
        chatTime: util.formatTime(new Date),
        ai_title: result.qTitle,
        endTitle: result.endTitle,
        closeTitle: result.closeTitle,
        closeQuestion: result.closeQuestion,
        taskQueueid: result.taskQueueid,
        mudid: result.mudid,
        ai_content: result.questionList && result.questionList.length > 0 ? result.questionList : null,
        // imagefiles: that.imagefiles,
        lasnAiAnswer: result.lasnAiAnswer,
      });
      that.setData({
        allContentList: that.data.allContentList
      })
      console.log("监听WebSocket 接受到服务器的消息事件==> ", res);
      console.log(JSON.parse(res.data))
      // 底部
      that.bottom();
    })

    // 监听录音开始
    recorderManager.onStart(() => {
      console.log('recorder start')
      this.setData({
        isSpeaking: true,
      })
    })

    // 监听录音结束
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      var _this = this;
      
      // 说明没有移动
      if (_this.data.currentGesture == 0){
        _this.speechRecognition(_this, res);
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.current_img_url, // 当前显示图片的http链接
      urls: this.data.imagefiles // 需要预览的图片http链接列表
    })
  },
  // 创建Socket
  webSocket: function() {
   
    let inputValue = this.data.input_value;
    let data = inputValue +
      "#" + mudid + "#" + email + "#" + uName + "#" + way;
    SocketTask = wx.connectSocket({
      url: url,
      data: data,
      header: {
        'content-type': 'application/json'
      },
      method: 'post',
      success: function(res) {
        console.log('WebSocket连接创建', res)
        socketOpen = true;
      },
      fail: function(err) {
        if (!socketOpen) {
          util.showModel('连接服务器失败.', '请下拉刷新试试.');
          return;
        }
        console.log(err)
      }
    })
   
  },

  getInputVlaue: function(e) {
    console.log(e)
    this.setData({
      input_value: e.detail.value
    });
  },

  // send AI question
  sendSocketMsg: function(e) {
    let numb = e.currentTarget.dataset.numb;
    if (!numb) return;
    this.sendSocketMessage(numb);
  },
  // send AI question 默认问题
  sendDefSocketMsg: function (e) {
    let msg = e.currentTarget.dataset.question;
    if (!msg) return;
    this.sendSocketMessage(msg);
  },

  // send my quesiton
  submitInputMessage: function() {
    // 点击未解决问题了
    if (feedbackFlg){
      this.feedbackSubmit();
    }else{ 
      let input_value = this.data.input_value;
      let data = input_value +
        "#" + mudid + "#" + email + "#" + uName + "#" + way;
      var that = this;
      that.data.allContentList.push({
        is_my: {
          inputValue: input_value,
          chatTime: util.formatTime(new Date)
        }
      });
      that.setData({
        allContentList: that.data.allContentList,
      })
      this.sendSocketMessage(data);
    }
  },

  // 发送未解决的问题
  feedbackSubmit:function(){
    util.showBusy('发送消息中...');
    console.log('点击未解决问题了Email:', email, wx.getStorageSync("ACCOUNT"));
    feedbackFlg = false;
    const folderName = util.uuid();
    let formData = {
      folderName: folderName,
      mudid: mudid,
      muName: encodeURI(firstName + " " + lastName),
      email: email,
      mudidType: 0,
      qtitle: encodeURI(''),
      tel: encodeURI(''),
      detailQuestion: encodeURI(this.data.input_value),
      submitSendMailUrl: config.config.service.host + '/miniProgram-submitSendMail', // 搞起url
    }

    wx.request({
      url: formData.submitSendMailUrl, //仅为示例，并非真实的接口地址
      data: formData,
      success: function (res) {
        var status = res.data.status;
        if (status) {
          wx.showModal({
            title: '发送成功.',
            content: '请下拉刷新后重新提问.',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                socketOpen = false;
                SocketTask.close();
                mudid = Math.floor(Math.random() * 9999999);
              } 
            }
          })
        } else {
          wx.showModal({
            title: '发送失败',
            content: '请联系管理员!',
          })
        }
      }, fail: function () {
        wx.showModal({
          title: '发送失败',
          content: '请联系管理员!',
        })
        wx.hideToast();
      },
      complete: function () {
        wx.hideToast();
      }
    })
  },

  // websockt发送消息
  sendSocketMessage: function(msg) {
    console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))

    if(socketOpen){
      util.showBusy('发送消息中...');
      let data = msg + "#" + mudid + "#" + email + "#" + uName + "#" + way;;
      SocketTask.send({
        data: data
      }, function (res) {
        console.log('已发送', res)
        }, function fail(res){
          console.log('发送失败', res)
      })
    }else{
      util.showModel('连接服务失败','请下拉刷新试试.');
    }
   
  },

  bottom: function() {
    wx.createSelectorQuery().select('#bottom').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 800
      })
    }).exec()
  },

  // 反馈未解决 废除
  // feedback: function() {
  //   wx.navigateTo({
  //     url: '../feedback/feedback?mudid=' + mudid + '&muName=' + firstName+" "+lastName + '&email=' + email
  //   })
  //   socketOpen = false;
  //   SocketTask.close();
  // },

  // 未解决 输入为解决问题.
  feedback: function() {
    feedbackFlg = true;
    let input_value = '未解决';
    let data = input_value +
      "#" + mudid + "#" + email + "#" + uName + "#" + way;
    var that = this;
    that.setData({
      allContentList: that.data.allContentList,
    })
    this.sendSocketMessage(data);
  },

  // 解决
  satisfiedTap:function(){
    // 不关闭 不知道客户咋想的; 后台关闭逻辑不走
    let data = "close" +
      "#" + mudid + "#" + email + "#" + firstName + "#" + lastName;
    if (this.data.closeQuestion){
      util.showModel('','该问题已解决.')
    }else{
      this.sendSocketMessage(data);
    }
  },

  // 评价 废除
  // satisfliedTap:function(e){
  //   let taskqueueid = e.currentTarget.dataset.taskqueueid;
  //   let mudid = e.currentTarget.dataset.mudid;
  //   console.log(taskqueueid, mudid);
  //   wx.navigateTo({
  //     url: '../satisfied/satisfied?taskqQueueId=' + taskqueueid + '&' + 'mudid=' + mudid
  //   })
  //   socketOpen = false;
  //   SocketTask.close();
  // },

 
  // rate 解决后继续评价
  ratetap:function(e){
    // socketOpen = false;
    // SocketTask.close();
    // mudid = Math.floor(Math.random() * 9999999);
  },

  // 选择什么方式发送消息
  click_way: function() {
    let _this = this;
    auth.checkPromission('scope.record', '将无法使用录音功能.', function(){
      _this.setData({
        keyboar_hidden: !_this.data.keyboar_hidden,
        voice_hidden: !_this.data.voice_hidden
      })
    })
    
  },

  // 发送语音操作
  // 按钮按下
  touchdown: function(e) {
    console.log("[Console log]:Touch down!Start recording!");
    let _this = this;
  
    // 隐藏取消说话图标
    _this.setData({
      lastY: e.touches[0].clientY,
      closeSpeaking: false,
      currentGesture:0
    })
    // 60scheck
    // this.touchDownTimer();
    // if (!voiceFlg) return;
    _this.speaking.call();
    recorderManager.start(options)
   
  },

  // 按钮松开
  touchup: function(e) {
    console.log("[Console log]:Touch up!Stop recording!");

    util.showBusy('发送消息中...');
   
    let currentY = e.changedTouches[0].clientY
    if (this.data.lastY - currentY   >  100 ){
      this.setData({
        closeSpeaking: true
      })
      this.data.currentGesture = this.data.lastY - currentY;
    }else{
      this.setData({
        closeSpeaking: false
      })
    }
    this.removeSpeaking();
    // 停止录音
    recorderManager.stop();
  },

  // 手指触摸动作被打断，如来电提醒，弹窗
  touchcancel:function(e){
    console.log('手指触摸动作被打断，如来电提醒，弹窗')
    console.log(e);
  },

  touchDownTimer: function() {
    let i = 0;
    timer60s = setInterval(function() {
      i++;
      if (i > MIN) {
        voiceFlg = false;
        wx.showModal({
          title: '录音失败',
          content: '录音不能大于60s.',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#09BB07',
        })
      }else{
        voiceFlg = true;
      }
    }, 1000);
  },

  // 麦克风帧动画 
  speaking: function() {
    var that = this;
    //话筒帧动画 
    var i = 0;
    that.speakerInterval = setInterval(function() {
      i++;
      i = i % 7;
      that.setData({
        speakerUrl: that.data.speakerUrlPrefix + i + that.data.speakerUrlSuffix,
      });
      console.log("[Console log]:Speaker image changing...");
    }, 300);
  },
  // 取消麦克风定时器
  removeSpeaking:function(){
    clearInterval(this.speakerInterval);
    this.setData({
      isSpeaking: false,
      speakerUrl: '../../style/img/speaker0.png',
    })
  },
  /** 语音识别 */
  speechRecognition : function(that, res) {
    console.log("语音识别");
    that.removeSpeaking();
    wx.uploadFile({
      url: config.config.service.voiceFileUploadUrl +'/miniProgram-voiceFileUpload',
      filePath: res.tempFilePath,
      name: 'file',
      // formData: {
      //   'user': 'test'
      // },
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        console.log(res); 
        let data = JSON.parse(res.data);
        let msg = '';
        console.log('res.result', data.result);
        console.log('res.data', data.err_no);
        console.log('res.data', data.err_msg);
        if (data && data.err_no == 0 && data.result){
          msg = data.result[0];
          that.data.allContentList.push({
            is_my: {
              inputValue: data.result[0],
              chatTime: util.formatTime(new Date),
            }
          });
        } else {
          that.data.allContentList.push({
            is_my: {
              inputValue: '语音识别失败了,重新试试看.',
              chatTime: util.formatTime(new Date)
            }
          });
        }
        that.setData({
          allContentList: that.data.allContentList
        })
        that.sendSocketMessage(msg)
      },
      fail: function () {
        console.log("语音识别失败");
        util.showModel('',"语音识别失败");
        
      },complete:function(){
        // 取消麦克风定时器
        that.removeSpeaking();
      }
    })
  },
})
